const {getUser, createUser, updateUser, getUserList} = require('../service/user')
const {createUserInfo} = require('../service/userInfo')
const {getUserAndRoleOne} = require('../service/userAndRole')
const {createUserAndRole} = require('../service/userAndRole')
const {SuccessModel, ErrorModel} = require('../model/ResModel')
const {
  registerUserNameNotExistInfo,
  registerUserNameExistInfo,
  registerFailInfo,
  loginFailInfo,
  changePasswordFailInfo
} = require('../model/ErrorInfo')
const doCrypto = require('../utils/cryp')

const isExist = async (userName) => {
  const userInfo = await getUser(userName)
  return userInfo ? new SuccessModel(userInfo) : new ErrorModel(registerUserNameNotExistInfo)
}

const register = async ({userName, password, nickName}) => {
  const userInfo = await getUser(userName)
  if (userInfo) {
    return new ErrorModel(registerUserNameExistInfo)
  }
  try {
    const newUser = await createUser({userName, password: doCrypto(password), nickName})
    await createUserInfo(newUser.id)
    await createUserAndRole({uid: newUser.id, rid: 2})
    return new SuccessModel()
  } catch (e) {
    return new ErrorModel(registerFailInfo)
  }

}

const login = async (ctx, userName, password) => {
  const userInfo = await getUser(userName, doCrypto(password))
  if (userInfo) {
    const role = await getUserAndRoleOne(userInfo.id)
    ctx.session.user = {
      user: {id: userInfo.id, userName: userInfo.userName, nickName: userInfo.nickName},
      userInfo: userInfo.userInfo.dataValues,
      role: role.role.dataValues
    }
    return new SuccessModel(ctx.session.user)
  } else {
    return new ErrorModel(loginFailInfo)
  }
}

const changePassword = async (ctx, {password, newPassword}) => {
  const {userName} = ctx.session.userInfo
  const result = await updateUser(
    {password: doCrypto(newPassword)},
    {userName, password: doCrypto(password)}
  )
  return result ? new SuccessModel() : new ErrorModel(changePasswordFailInfo)
}

const logout = async (ctx) => {
  delete ctx.session.user
  return new SuccessModel()
}

const isLogin = async (ctx) => {
  if (ctx.session.user) {
    return new SuccessModel(ctx.session.user)
  } else {
    return new ErrorModel(changePasswordFailInfo)
  }
}

const getUsers = async ({userName = '', nickName = '', pageIndex = 0, pageSize = 10, createTime = []}) => {
  const result = await getUserList({userName, nickName, pageIndex, pageSize, createTime})
  return result ? new SuccessModel(result) : new ErrorModel(changePasswordFailInfo)
}

module.exports = {
  isExist,
  register,
  login,
  changePassword,
  logout,
  isLogin,
  getUsers
}
